package com.jiudengnile.liushu.web.common.base;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wint.help.biz.result.Result;
import wint.help.biz.result.ResultCode;
import wint.help.biz.result.ResultType;
import wint.help.biz.result.results.CommonResultCodes;
import wint.mvc.flow.FlowData;
import wint.mvc.template.Context;

public class BaseAction {
	
protected final Logger log = LoggerFactory.getLogger(this.getClass());
	
	protected Logger getLogger() {
		return log;
	}
	
	/**
	 * 处理出错
	 * @param result
	 * @param rundata
	 * @param templateContext
	 */
	protected void handleError(Result result, FlowData flowData, Context context) {
		ResultCode resultCode = result.getResultCode();
		if (resultCode == null) {
			resultCode = CommonResultCodes.SYSTEM_ERROR;
		}
		if (result.getResultType() == ResultType.COMMON_TARGET) {
			flowData.setTarget("error");
		}
		context.put("resultCode", resultCode);
	}
	
	protected void sendToError(FlowData flowData, Context context, ResultCode resultCode) {
		flowData.setTarget("error");
		context.put("resultCode", resultCode);
	}
	
	
	/**
	 * 把result中的对象放入到context
	 * @param result
	 * @param templateContext
	 * @param name
	 * @return
	 */
	protected Object result2Context(Result result, Context context, String name) {
		Object value = result.getModels().get(name);
		context.put(name, value);
		return value;
	}
	
	protected void result2Context(Result result, Context context) {
		for (Map.Entry<String, Object> entry : result.getModels().entrySet()) {
			context.put(entry.getKey(), entry.getValue());
		}
	}
	
	protected void handleResult(Result result, FlowData flowData, Context context) {
		if (result.isSuccess()) {
			this.result2Context(result, context);
		} else {
			this.handleError(result, flowData, context);
		}
	}

}
